package com.lijun.SpringBootJavaFX.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lijun.SpringBootJavaFX.controller.person.PeopleController;
import com.lijun.SpringBootJavaFX.service.person.PersonService;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.TextArea;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
@FXMLController
public class Client1Controller implements Initializable{

    @FXML
    private BarChart<Number,String> barChart;

    @FXML
    private NumberAxis yAxis;

    @FXML
    private CategoryAxis xAxis;

    @FXML
    private TextArea barChartJsonData;

    @Autowired
    PeopleController peopleController;


    @Autowired
    PersonService personService;



    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initBarChart();
    }

    public void initBarChart(){

        barChart.getData().remove(0, barChart.getData().size());

        ObjectMapper om = new ObjectMapper();
        List data = null;
        try {
            data = om.readValue(barChartJsonData.getText(), List.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        XYChart.Series[] seriess = new XYChart.Series[data.size()];
        for (int i = 0; i < data.size(); i++) {
            Map<String,Object> map = (Map<String, Object>) data.get(i);
            XYChart.Series series = new XYChart.Series();
            series.setName((String) map.get("name"));
            List<String> xValues1 = (List) map.get("xValues");
            List<Double> yValues1 = (List) map.get("yValues");
            for (int j = 0; j < xValues1.size(); j++) {
                String xValue = xValues1.get(j);
                series.getData().add(new XYChart.Data(xValue, yValues1.get(j)));
            }
            seriess[i] = series;
        }

        barChart.setTitle("Country Summary");
        yAxis.setLabel("Value");
        yAxis.setTickLabelRotation(90);
        xAxis.setLabel("Country");

        barChart.getData().addAll(seriess);
    }

    public void commitBarChartJsonData(ActionEvent actionEvent){
        initBarChart();
    }

    public void openAddPersonWindow(ActionEvent actionEvent){
        peopleController.openWindow(actionEvent, null);
    }

    public void openUpdatePersonWindow(ActionEvent actionEvent){
        peopleController.openWindow(actionEvent, "1");
    }

}
